package com.time.gateway.auth;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.time.gateway.constants.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * [Sa-Token 权限认证] 配置类
 *
 * @author: HuangQi
 * @date: Created in 16:31 2025/8/27
 * @description: [Sa-Token 权限认证] 配置类
 */

@Configuration
@Slf4j
public class SaTokenConfigure {

    // 注册 Sa-Token全局过滤器
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                .addInclude("/**")
                .addExclude("/favicon.ico")
                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    log.info("SaTokenConfigure.getSaReactorFilter---------- 前端访问path" + SaHolder.getRequest().getRequestPath());
                    // 登录校验 -- 拦截所有路由，并排除/user/doLogin 用于开放登录
                    SaRouter.match("/auth/**", "/auth/user/doLogin", r -> StpUtil.checkRole("normal_user"));
                    SaRouter.match("/oss/**", r -> StpUtil.checkLogin());
                    SaRouter.match("/admin/**", r -> StpUtil.checkRole("admin"));
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e -> {
                    if (e instanceof NotLoginException) {
                        return SaResult.error(GatewayConstant.MSG_NOT_LOGIN);
                    } else if (e instanceof NotRoleException) {
                        return SaResult.error(GatewayConstant.MSG_UNAUTHORIZED);
                    }
                    return SaResult.error("认证失败: " + e.getMessage());
                });
    }
}
